package com.example.demo.security.service;

import com.example.demo.admin.bean.AdminBean;
import com.example.demo.admin.service.AdminService;
import org.hibernate.mapping.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class MyUserDetailsService implements UserDetailsService {


    @Autowired
    private AdminService adminService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

      AdminBean adminBean = adminService.findByUserName(username);
       if (adminBean!=null) {
           List<MyGrantedAuthority> list = adminBean.getSecurtiyAdminRoleBeans().parallelStream().map(b -> new MyGrantedAuthority(b.getSecurityRoleBean().getRoleName())).collect(Collectors.toList());
           return new User(username, adminBean.getPassword(), adminBean.getState() == 0, true, true, true, list);
       }else{
          throw new UsernameNotFoundException("没有该用户");
       }
    }
}
